//
//  HomeViewController.m
//  AppointmentForCar
//
//  Created by Herron on 16/10/2.
//  Copyright © 2016年 Herron. All rights reserved.
//

#import "HomeViewController.h"
#import "MyCenterViewController.h"
#import "HomeHeaderView.h"
#import "HomeCell.h"
#import "HomeViewModel.h"
#import "HomeTableHeaderView.h"
#import "HomeTableViewCell.h"
#import "OrderInfoView.h"
#import "PushManager.h"
#import "grabSingleView.h"
#import "CallCarModel.h"
#import "WQPlaySound.h"

#define kSectionHeight kScaleHeight(180)
#define kHomeTableViewCellId @"HomeTableViewCell"
@interface HomeViewController ()<UITableViewDelegate, UITableViewDataSource, GrabSingleViewDelegate, OrderInfoViewDelegate>

@property (nonatomic , weak) UITableView *homeTableView;        // tableview
@property (nonatomic , weak) HomeTableHeaderView *headerView;   // tableview header
@property (nonatomic , strong) HomeViewModel *model;            // viewModel
@property (nonatomic , weak) UIButton *outCarButton;                  // 出车按钮
@property (nonatomic , weak) UIButton *closedButton;            // 关闭抢单窗口按钮
@property (nonatomic , weak) UIImageView *backImage;            // 背景图片
@property (nonatomic , weak) OrderInfoView *orderInfoView;      // 订单信息视图
@property (nonatomic , weak) GrabSingleView *grabSingView;      // 抢单窗口
@property (nonatomic , assign) BOOL isAccept;                   // 是否接受

@end

@implementation HomeViewController

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"myCenter"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(myCenter)];
    
    // 获取到推送
    __weak typeof(self) weakSelf = self;
    [[PushManager sharePushManager] getCallPassengerInfo:^(CallCarModel *model) {
        __strong typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf findOrderWithModel:model];

    }];

    // 通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(reloadAvatar:) name:kNoticeChangeAvatarImage object:nil];
    [center addObserver:self selector:@selector(reloadName:) name:kNoticeChangeName object:nil];

    // 加载tableview
    [self.homeTableView reloadData];
    
    // 获取订单历史
    [self.model getDriverHistoricalRecordWithId:[UserAccountManager shareUserManager].user.driverId complete:^(id error) {
        [self.homeTableView reloadData];
    }];
    
    // 加载背景视图
    self.backImage.image = [UIImage imageNamed:@"background"];
    
    // 获取用户信息
    [self.model getDriverBriefInformationWithId:[UserAccountManager shareUserManager].user.driverId complete:^(id error) {
      self.headerView.model = self.model.driver;
    }];
    
    // 加载出车按钮
    [self displayOurCar];
    
}

- (void)viewWillAppear:(BOOL)animated {
    [self.mm_drawerController setOpenDrawerGestureModeMask:MMOpenDrawerGestureModeNone];
    self.navigationController.navigationBar.translucent = NO;
    
    UIView *titleView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 36, 36)];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 36, 36)];
    [imageView setImage:[UIImage imageNamed:@"m-icon"]];
    imageView.layer.cornerRadius = 18;
    imageView.layer.masksToBounds = YES;
    [titleView addSubview:imageView];
    self.navigationItem.titleView = titleView;
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNoticeChangeAvatarImage object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kNoticeChangeName object:nil];
}

#pragma mark - <UITableViewDateSource>
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.model.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    HomeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:kHomeTableViewCellId];
    cell.model = self.model.dataArray[indexPath.row];
    return cell;
}

#pragma mark - <UIScrollViewDelegate>
-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    __weak typeof(self) weakSelf = self;
    if(velocity.y > 0) {
        if(!_outCarButton) {
            return;
        }
        [_outCarButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(weakSelf.view.mas_bottom);
        }];
        [UIView animateWithDuration:0.25f animations:^{
            [self.view layoutIfNeeded];
        } completion:^(BOOL finished) {
            [_outCarButton removeFromSuperview];
        }];
    } else {
        [self.outCarButton mas_updateConstraints:^(MASConstraintMaker *make) {
            make.bottom.equalTo(weakSelf.view.mas_bottom).mas_offset(-kScaleHeight(40)).priority(750);
        }];
       [UIView animateWithDuration:0.25f animations:^{
           [weakSelf.view layoutIfNeeded];
       }];
    }
}

#pragma mark - <GrabSingleViewDelegate>
#pragma mark 抢单
- (void)grabSingle:(GrabSingleView *)view {
   
    // 需要订单ID
    [self.model robOrderWithReservationId:self.orderInfoView.model.reservationId complete:^(id error) {
        if(error) {
            [HUDManager showWarningWithError:error];
            [_grabSingView removeToWindos];
            [self.orderInfoView removeFromToWindows];
            [self hideContent];
            [self displayOurCar];
            self.closedButton.hidden = NO;
            _isAccept = YES;
            
        } else {
            _outCarButton.selected = !_outCarButton.selected;
            [self.orderInfoView removeFromToWindows];
            [_grabSingView removeToWindos];
            [self showContent];
            // TODO: 抢单成功
            [HUDManager showWarningWithError:@"抢单成功"];
            // 刷新订单
            [self.model getDriverHistoricalRecordWithId:[UserAccountManager shareUserManager].user.driverId complete:^(id error) {
                [self.homeTableView reloadData];
            }];
            // 获取用户信息
            [self.model getDriverBriefInformationWithId:[UserAccountManager shareUserManager].user.driverId complete:^(id error) {
                self.headerView.model = self.model.driver;
            }];
        }
    }];
}

#pragma mark 倒计时结束
- (void)countDownStop {
    [self.orderInfoView removeFromToWindows];
    [self displayOurCar];
    self.closedButton.hidden = NO;
    [self hideContent];
    _isAccept = YES;
}

#pragma mark - <OrderInfoViewDelegate>
#pragma mark 点击抢单视图的叉
- (void)remove {
    [_grabSingView removeToWindos];
    [self hideContent];
    [self displayOurCar];
    self.closedButton.hidden = NO;
    _isAccept = YES;
}

#pragma mark - Event Method
#pragma mark 刷新头像
- (void)reloadAvatar:(NSNotification *)sender {
    [self.headerView setupIcon:[UserAccountManager shareUserManager].user.driverAvatarUrl];
}

#pragma mark 刷新名字
- (void)reloadName:(NSNotification *)sender {
    [self.headerView setupName:[UserAccountManager shareUserManager].user.driverNickName];
}

#pragma mark 个人中心
- (void)myCenter {
    [self.mm_drawerController toggleDrawerSide:MMDrawerSideLeft animated:YES completion:nil];
}

#pragma mark 出车
- (void)outCarEvent:(UIButton *)sender {
    NSString *status = [UserAccountManager shareUserManager].user.status;
    if ([status isEqualToString:@"0"]) {
        [HUDManager showWarningWithText:@"您的账号正在审核中，暂时不能出车"];
    } else if ([status isEqualToString:@"1"]) {
        [PushManager sharePushManager].pushSwith = !sender.selected;
        if(!sender.selected) {
            // 隐藏
            // 出车了
            [self.model driverOutCarWithdriverIdWithcomplete:^(id error) {
                [self hideContent];
                _isAccept = YES;
            }];
        } else {// 显示
            // 收车了
            [self.model driverBackCarWithdriverIdWithcomplete:^(id error) {
                [self showContent];
                _isAccept = NO;
            }];
        }
        sender.selected = !sender.selected;
    } else if ([status isEqualToString:@"2"]) {
        [HUDManager showWarningWithText:@"您的账号审核未通过，不能出车"];
    } else if ([status isEqualToString:@"3"]) {
        [HUDManager showWarningWithText:@"您的账号正在审核中，暂时不能出车"];
    }
}

#pragma mark 收车
- (void)closedEvent:(UIButton *)sender {
    [self showContent];
    self.outCarButton.selected = !self.outCarButton.selected;
    [PushManager sharePushManager].pushSwith = !self.outCarButton.selected;
    _isAccept = NO;
}

#pragma - Private Method
#pragma mark 显示出车按钮
- (void)displayOurCar {
    __weak typeof(self) weakSelf = self;
    [self.outCarButton mas_updateConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakSelf.view.mas_bottom).mas_offset(-kScaleHeight(40)).priority(750);
    }];
}

#pragma mark 出现订单
- (void)findOrderWithModel:(CallCarModel *)model {
    if(!_isAccept) {
        return;
    }
    // 您有一条新订单！
    WQPlaySound *sound = [[WQPlaySound alloc] initForPlayingVibrate];
    [sound play];
    
    __weak typeof(self) weakSelf = self;
    self.orderInfoView.model = model;
    
    [self.outCarButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(weakSelf.view);
        make.bottom.equalTo(weakSelf.orderInfoView.displayView.mas_bottom).mas_offset(kScaleHeight(35));
        make.size.mas_equalTo((CGSize){kScaleWidth(70),kScaleWidth(70)});
    }];
    self.closedButton.hidden = YES;
//    self.outCarButton.hidden = YES;
    self.grabSingView.delegate = self;
    _isAccept = NO;
    [UIView animateWithDuration:0.25f animations:^{
        [weakSelf.view layoutIfNeeded];
        self.orderInfoView.alpha = 1;
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
        [_closedButton removeFromSuperview];
    }];
}

#pragma mark 隐藏首页
- (void)hideContent {
    __weak typeof(self) weakSelf = self;
    [_homeTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(weakSelf.view.mas_bottom);
        make.right.left.equalTo(weakSelf.view);
    }];
    [_headerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(weakSelf.view.mas_top);
        make.right.left.equalTo(weakSelf.view);
    }];
    [self.closedButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo((CGSize){kScaleWidth(55),kScaleWidth(55)});
        make.right.equalTo(weakSelf.view.mas_right).mas_offset(-kScaleWidth(20));
        make.bottom.equalTo(weakSelf.view.mas_bottom).mas_offset(-kScaleHeight(40));
    }];
    [UIView animateWithDuration:0.25f animations:^{
        [self.view layoutIfNeeded];
    } completion:^(BOOL finished) {
    }];
}

#pragma mark 显示首页
- (void)showContent {
    __weak typeof(self) weakSelf = self;
    [self.headerView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(weakSelf.view);
    }];
    [self.homeTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.equalTo(weakSelf.view);
        make.top.equalTo(weakSelf.headerView.mas_bottom);
    }];
    [self.closedButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo((CGSize){kScaleWidth(55),kScaleWidth(55)});
        make.top.equalTo(weakSelf.view.mas_bottom);
        make.right.equalTo(weakSelf.view.mas_right).mas_offset(-kScaleWidth(20));
    }];
    [UIView animateWithDuration:0.25f animations:^{
        [weakSelf.view layoutIfNeeded];
        _orderInfoView.alpha = 0;
    } completion:^(BOOL finished) {
        [_orderInfoView removeFromSuperview];
    }];
    [self displayOurCar];
}


/**
 *  抢单
 */
- (void)grabSingle {
    
}


#pragma mark - setter and getter
#pragma mark 主视图
- (UITableView *)homeTableView {
    if(!_homeTableView) {
        UITableView *tableview = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
        tableview.backgroundColor = [UIColor clearColor];
        tableview.delegate = self;
        tableview.dataSource = self;
        tableview.separatorColor = [UIColor clearColor];
        tableview.estimatedRowHeight = 100;
        tableview.rowHeight = UITableViewAutomaticDimension;
        tableview.tableFooterView = [[UIView alloc] init];
        [tableview registerClass:[HomeTableViewCell class] forCellReuseIdentifier:kHomeTableViewCellId];
        self.view.addSubview(tableview);
        __weak typeof(self) weakSelf = self;
        [tableview mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.bottom.right.equalTo(weakSelf.view);
            make.top.equalTo(weakSelf.headerView.mas_bottom);
        }];
        _homeTableView = tableview;
    }
    return _homeTableView;
}

#pragma mark 头部视图
- (HomeTableHeaderView *)headerView {
    if(!_headerView) {
        HomeTableHeaderView *header = [[HomeTableHeaderView alloc] init];
        self.view.addSubview(header);
        __weak typeof(self) weakSelf = self;
        [header mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.right.equalTo(weakSelf.view);
        }];
        _headerView = header;
    }
    return _headerView;
}

#pragma mark 逻辑模型
- (HomeViewModel *)model {
    if(!_model) {
        _model = [[HomeViewModel alloc] init];
    }
    return _model;
}

#pragma mark 出车按钮
- (UIButton *)outCarButton {
    if(!_outCarButton) {
        UIButton * sender = [UIButton buttonWithType:UIButtonTypeCustom];
        [sender setBackgroundImage:[UIImage imageNamed:@"action"] forState:UIControlStateNormal];
        [sender addTarget:self action:@selector(outCarEvent:) forControlEvents:UIControlEventTouchUpInside];
        [sender setTitle:@"听单中..." forState:UIControlStateSelected];
        sender.titleLabel.font = kAppFontSize(13);
        [sender setBackgroundImage:[UIImage imageNamed:@"buttonBg"] forState:UIControlStateSelected];
        self.view.addSubview(sender);
        __weak typeof(self) weakSelf = self;
        [sender mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(weakSelf.view);
            make.size.mas_equalTo((CGSize){kScaleWidth(70),kScaleWidth(70)});
            make.top.equalTo(weakSelf.view.mas_bottom).priority(500);
            make.bottom.equalTo(weakSelf.view.mas_bottom).mas_offset(-kScaleHeight(40)).priority(500);
        }];
        [weakSelf.view layoutIfNeeded];
        _outCarButton = sender;
    }
    return _outCarButton;
}

#pragma mark 关闭窗口
- (UIButton *)closedButton {
    if(!_closedButton) {
        UIButton * sender = [UIButton buttonWithType:UIButtonTypeCustom];
        [sender setBackgroundImage:[UIImage imageNamed:@"whiteButton"] forState:UIControlStateNormal];
        [sender addTarget:self action:@selector(closedEvent:) forControlEvents:UIControlEventTouchUpInside];
        [sender setTitle:@"收车" forState:UIControlStateNormal];
        sender.titleLabel.font = kAppFontSize(13);
        [sender setTitleColor:[UIColor colorWithString:@"#EF9541"] forState:UIControlStateNormal];
        self.view.addSubview(sender);
        __weak typeof(self) weakSelf = self;
        [sender mas_makeConstraints:^(MASConstraintMaker *make) {
            make.size.mas_equalTo((CGSize){kScaleWidth(55),kScaleWidth(55)});
            make.top.equalTo(weakSelf.view.mas_bottom);
            make.right.equalTo(weakSelf.view.mas_right).mas_offset(-kScaleWidth(20));
        }];
        [weakSelf.view layoutIfNeeded];
        _closedButton = sender;
    }
    return _closedButton;
}

#pragma mark 订单信息视图
- (OrderInfoView *)orderInfoView {
    if(!_orderInfoView) {
        OrderInfoView * view = [[OrderInfoView alloc] init];
        [self.view insertSubview:view atIndex:1];
        view.alpha = 0;
        _orderInfoView = view;
        _orderInfoView.delegate = self;
        [self.view layoutIfNeeded];
    }
    return _orderInfoView;
}

#pragma mark 背景视图
- (UIImageView *)backImage {
    if(!_backImage) {
        UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"background"]];
        [self.view insertSubview:image atIndex:0];
        __weak typeof(self) weakSelf = self;
        [image mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(weakSelf.view);
        }];
        _backImage = image;
    }
    return _backImage;
}

#pragma mark 抢单视图
- (GrabSingleView *)grabSingView {
    if(!_grabSingView) {
        GrabSingleView *view = [[GrabSingleView alloc] init];
        self.view.addSubview(view);
        [self.view insertSubview:view aboveSubview:self.orderInfoView.displayView];
        __weak typeof(self) weakSelf = self;
        view.backImage = [UIImage imageNamed:@"buttonBg"];
        [view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(weakSelf.outCarButton);
        }];
        [self.view layoutIfNeeded];
        _grabSingView = view;
    }
    return _grabSingView;
}


@end
